package co.rcantor.dev.formularios;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;

public class DatosIniciales extends Activity{

	private static String pais;
	
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.datosi);

        Spinner spinner = (Spinner) findViewById(R.id.paises);
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
                this, R.array.paises, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
        spinner.setOnItemSelectedListener(new MyOnItemSelectedListener());
        
        Button guardar = (Button)findViewById(R.id.ok);
        guardar.setOnClickListener(saveListener); 
        
        Button cancelar = (Button)findViewById(R.id.cancel);
        cancelar.setOnClickListener(cancelListener);   
        
        
    }
	
	private OnClickListener saveListener = new OnClickListener() {
	    public void onClick(View v) {
	    	
	    	String FILENAME = "SIASARsave.txt";
	    	String string = "";
	    	
	    	string = string + "\nFecha de aplicacion: "+ Registro.getFecha() 
	    			+"\nEncuestador: " + Registro.getUser1()
	    			+"\nNombre usuario:" + Registro.getUser2()
	    			+"\nAmbiente sano: " + DatosFinales.getAmbiente()
	    			+"\nPais: " + DatosIniciales.getPais() + "\n";
	    	
	         ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
	         nameValuePairs.add(new BasicNameValuePair("fecha",Registro.getFecha()));
	         nameValuePairs.add(new BasicNameValuePair("encuestador",Registro.getUser1()));
	         nameValuePairs.add(new BasicNameValuePair("nombre",Registro.getUser2()));
	         nameValuePairs.add(new BasicNameValuePair("ambiente",DatosFinales.getAmbiente()));
	         nameValuePairs.add(new BasicNameValuePair("pais",DatosIniciales.getPais()));
	         InputStream is = null; 
	         try{
	                 HttpClient httpclient = new DefaultHttpClient();
	                 HttpPost httppost = new HttpPost("http://www.siasar.org/prueba-android.php");
	                 httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
	                 HttpResponse response = httpclient.execute(httppost);
	                 HttpEntity entity = response.getEntity();
	                 is = entity.getContent();
	                 is.close();
	         }catch(Exception e){
	                 Log.e("log_tag", "Error in http connection "+e.toString());
	         }	        
	        	                 
	    	FileOutputStream fos = null;
			try {		    		
				fos = openFileOutput(FILENAME, Context.MODE_APPEND);
				fos.write(string.getBytes());
		    	fos.close();
		    	Toast.makeText(DatosIniciales.this, string, Toast.LENGTH_LONG).show();
		    	
		    	String state = Environment.getExternalStorageState();

		    	if (Environment.MEDIA_MOUNTED.equals(state)) {
		    		String basedir = Environment.getExternalStorageDirectory().getAbsolutePath();
		    		File f = new File(basedir, FILENAME);
		    		
		    		fos = new FileOutputStream(f, true);
		    		fos.write(string.getBytes());
			    	fos.close();
		    	}
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}catch (IOException e) {
				e.printStackTrace();
			}
			
	    }
	};
	
	private OnClickListener cancelListener = new OnClickListener() {
	    public void onClick(View v) {
	    	Toast.makeText(DatosIniciales.this, "Se cerrara la aplicacion", Toast.LENGTH_SHORT).show();
	    	System.exit(0);
	    }
	};

	public static String getPais() {
		return pais;
	}

	public static void setPais(String pais) {
		DatosIniciales.pais = pais;
	}
	   
	public class MyOnItemSelectedListener implements OnItemSelectedListener {

	    public void onItemSelected(AdapterView<?> parent,
	        View view, int pos, long id) {
	    	setPais(parent.getItemAtPosition(pos).toString());
	    }

	    public void onNothingSelected(AdapterView<?> parent) {
	      
	    }
	}
	
}
